package org.example.learn;

import java.lang.ref.SoftReference;

/**
 * 强引用的Demo
 */
public class StrongReferenceDemo {
    public static void main(String[] args) {
        Object obj1=new Object();
        Object obj2=obj1;
        obj1=null;
        System.gc();
        System.out.println(obj2);
    }
}


class StrongReferenceDemo2{

    /**
     * 内存够用的时候就保留，不够的时候就回收
     */
    public static void softref_memory_enough(){
        Object obj1=new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj1);
        System.out.println(obj1);
        System.out.println(softReference.get());

        obj1=null;
        System.gc();
        System.out.println(obj1);
        System.out.println(softReference.get());

    }

    /**
     * 内存不够的时候
     * JVM配置，故意产生大对象并配置小内存，让它内存不够用了导致OOM，看软引用的情况
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    public static void softref_memory_notEnough(){
        Object obj1=new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj1);
        System.out.println(obj1);
        System.out.println(softReference.get());

        obj1=null;
        try{
            byte[] bytes=new byte[30*1024*1024];
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(obj1);
            System.out.println(softReference.get());
        }

    }

    public static void main(String[] args) {
//        softref_memory_enough();
        softref_memory_notEnough();

    }

}
